<?php

class Admin_AuthController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }

    public function loginAction()
    {
        try {
            $auth = Zend_Auth::getInstance();
            if($auth->hasIdentity()){
                $role = $auth->getIdentity()->user_role;
                if($role == 'admin'){
                    $this->redirect(array('module'=>'admin', 'controller'=>'index', 'aciton'=>'index'));
                }
                else{
                    $this->redirect(array('module'=>'default', 'controller'=>'index', 'action'=>'index'));
                }
            }
            else{
                $form = new Admin_Form_Login();
                $this->view->form = $form;
                
                if($this->_request->isPost()){
                    if($form->isValid($this->_request->getPost())){
						$username = $form->getValue("name");
						$password = $form->getValue("pass");
                        $adapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
                        $adapter->setTableName('user')
                                ->setIdentityColumn('user_email')
                                ->setCredentialColumn('password');
                        $adapter->setCredential(md5($password))
                                ->setIdentity($username);
                        
                        $result = $auth->authenticate($adapter);
                        if($result->isValid()){
                            $identity = $adapter->getResultRowObject(null, array('pass'));
                            $auth->getStorage()->write($identity);
                            $this->_helper->redirector('index', 'product', 'admin');
                        }
                        else {
                            $form->pass->clearErrorMessages();
                            $form->pass->addError("Sai tên đăng nhập hoặc mật khẩu");
                        }
                    }
                }
            }
        }
        catch (Zend_Exception $ex){
            echo $ex;
        }
    }

    public function logoutAction()
    {
        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $this->_helper->redirector('index', 'index', 'default');
    }


}





